package com.etc.log;

import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.File;
import java.io.FilenameFilter;
import java.util.TimerTask;
import java.util.UUID;

/**
 * @author 杰哥
 * @Title: Log
 * @ProjectName worldcount
 * @Description: TODO
 * @date 2019/8/2010:41
 */
public class Log extends TimerTask {
    @Override
    public void run() {
        try {
            File file = new File("E:\\log\\access");
            //过滤出后缀为.log的文件
            File [] files = file.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    //endsWith判断后缀
                    if(name.endsWith(".log")){
                        return true;
                    }else {
                        return false;
                    }

                }
            });

            File file1 = new File("E:\\log\\etc");
            for(File files1 :files){
                //移动到待上传文件
                FileUtils.moveFileToDirectory(files1,file1,true);
            }
            //创建一个hdfs客户端对象
            Configuration config = new Configuration();
            config.set("fs.defaultFS","hdfs://192.168.88.5:9000");
            FileSystem fs = FileSystem.get(config);

            //判断hdfs目录是否存在  不存在则创建
            Path path = new Path("/logger");
            if(!fs.exists(path)){
                fs.mkdirs(path);

            }
            //判断备份目录是否存在  不存在则创建
            File backupDir = new File("E:\\log\\back");
            if(!backupDir.exists()){
                backupDir.mkdir();
            }
            File[] files1 = file1.listFiles();
            for(File file2:files1){
                Path destPath = new Path(path + "/" + "jie_log_" + UUID.randomUUID() + ".log");
                fs.copyFromLocalFile(new Path(file2.getAbsolutePath()),destPath);
                //显示上传文件完成
                System.out.println("上传文件完成:" + file2.getAbsolutePath() + "-->" + destPath);
                FileUtils.moveFileToDirectory(file2,backupDir,true);
                //显示备份完成
                System.out.println("文件备份完成" + file2.getAbsolutePath() + "-->" + backupDir);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
